package main

import (
	"context"
	"go_iot/pkg/config"
	"go_iot/pkg/global"
	"os"
	"os/signal"
	"syscall"

	"go_iot/server"
	"net/http"
	"time"
)

func main() {

	var err error
	global.Conf = &config.Config{}
	global.Conf.Init()
	dbGorm := &config.DbCorm{
		Dbtype:       global.Conf.Server.Dbtype,
		Maxidleconns: global.Conf.Server.Maxidleconns,
		Maxopenconns: global.Conf.Server.Maxopenconns,
	}
	if dbGorm.Dbtype == "mysql" {
		dbGorm.Dsn = global.Conf.Mysql.Dsn()
	} else {
		dbGorm.Dsn = global.Conf.Postgresql.Dsn()
	}

	//日志
	global.Log = config.InitLog(global.Conf.LogInfo.Path)
	//关系数据库初始化
	global.Db = dbGorm.InitDb()
	//mangodb初始化
	global.MongoDb, err = global.Conf.MongoDb.GetMongoClient()

	if err != nil {
		panic("mongodb错误连接" + err.Error())
	}
	//redis初始化
	global.Rdb, err = global.Conf.RedisDb.InitRedisClient()
	if err != nil {
		panic("redis错误连接" + err.Error())
	}

	app := server.NewApp()

	tcp, err := server.NewServer(":5656")
	if err != nil {
		panic("tcp服务启动失败")
	}

	go tcp.Start()

	global.Log.Info("api服务启动")
	srv := &http.Server{
		Addr:           ":8080",
		Handler:        app,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	idle := make(chan struct{})
	go func() {
		signalNotify := make(chan os.Signal, 1)
		signal.Notify(signalNotify, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
		<-signalNotify
		global.Log.Info("api服务关闭")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		if err := global.MongoDb.Client().Disconnect(ctx); err != nil {
			global.Log.Warn("关闭mongodb错误" + err.Error())
		}
		tcp.Stop()
		if err := srv.Shutdown(ctx); err != nil {
			global.Log.Warn("关闭api服务错误" + err.Error())
		}
		close(idle)
	}()

	srv.ListenAndServe()
	<-idle
}
